package gw.com.android.ui.me;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.ui.BaseActivity;
import gw.com.android.utils.ImageUtil;
import www.com.library.util.PermissionUtil;
import www.com.library.view.BtnClickListener;

/**
 * 选择本地相册中的图片
 *
 * @author jett
 * @since 2017-10-18.
 */
public class AlbumActivity extends BaseActivity {

    private static final int REQUEST_PREVIEW = 66;

    private static final int DEFAULT_COLUMN_COUNT = 3;
    public static final String COLUMN_COUNT = "column_count";
    public static final String SHOW_CAMERA = "show_camera";
    public static final String PICKED_LIST = "picked_list";

    private AlbumAdapter mAdapter;
    private int columnNum; // 每行显示多少张图片
    private boolean showCamera; // 是否显示相机
    private String takePhotoPath;
    private PermissionUtil mAccessCameraPermission;

    @BindView(R.id.tv_complete)
    TextView tvComplete;
    @BindView(R.id.tv_preview)
    TextView tvPreview;
    @BindView(R.id.rv_album)
    RecyclerView recyclerView;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_album;
    }

    @Override
    protected void setAcitivityParam() {
        columnNum = getIntent().getIntExtra(COLUMN_COUNT, DEFAULT_COLUMN_COUNT);
        showCamera = getIntent().getBooleanExtra(SHOW_CAMERA, true);
    }

    @Override
    protected void initLayoutView() {
        mTitleBar.setAppTitle(R.string.feedback_album);
        mTitleBar.setRightText(R.string.btn_cancel);
        recyclerView.setLayoutManager(new GridLayoutManager(this, columnNum));
        ArrayList<String> picked = getIntent().getStringArrayListExtra(PICKED_LIST);
        notifyTextChange(picked == null ? 0 : picked.size());
        mAdapter = new AlbumAdapter(this, showCamera, columnNum, 3).addPicked(picked);
        recyclerView.setAdapter(mAdapter);

        mTitleBar.setBtnClickListener(new BtnClickListener() {
            @Override
            public void onBtnClick(int viewID) {
                finish();
            }
        });
    }

    @Override
    protected void initViewData() {
        getSupportLoaderManager().initLoader(0, null, mLoaderCallback);
        mAdapter.setOnAlbumClickListener(new AlbumAdapter.OnAlbumClickListener() {
            @Override
            public void onCamera() {
                requestCameraPermission();
            }

            @Override
            public void onImage(AlbumAdapter adapter, int position, String path) {
                int size = adapter.picked.size();
                notifyTextChange(size);
            }
        });
    }

    private void notifyTextChange(int count) {
        String text = AppMain.getApp().getString(R.string.btn_confirm);
        if (count <= 0) {
            tvComplete.setText(text);
            tvComplete.setAlpha(0.4F);
            tvComplete.setClickable(false);
            tvPreview.setClickable(false);
            tvPreview.setAlpha(0.5F);
        } else {
            tvComplete.setText(text.concat(String.format(Locale.getDefault(), "(%d)", count)));
            tvComplete.setAlpha(1F);
            tvComplete.setClickable(true);
            tvPreview.setClickable(true);
            tvPreview.setAlpha(1F);
        }
    }

    private void requestCameraPermission() {
        mAccessCameraPermission = new PermissionUtil();
        mAccessCameraPermission.requestPermission(this, Manifest.permission.CAMERA, AppContances.REQUEST_PERMISSION_ACCESS_CAMERA, new PermissionUtil.OnRequestPermissionResult() {
            @Override
            public void onGranted() {
                launchCamera();
            }

            @Override
            public void onRefused() {
            }
        });
    }

    private void launchCamera() {
        try {
            takePhotoPath = ImageUtil.getNewPhotoPath();
            Intent mSourceIntent = ImageUtil.takeBigPicture(this, takePhotoPath);
            startActivityForResult(mSourceIntent, FeedbackActivity.REQUEST_CAMERS);
        } catch (Exception ignore) {
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (mAccessCameraPermission != null) {
            mAccessCameraPermission.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == FeedbackActivity.REQUEST_CAMERS) {
            if (TextUtils.isEmpty(takePhotoPath)) {
                return;
            }
            ArrayList<String> list = mAdapter == null ? null : mAdapter.getPicked();
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(takePhotoPath);
            Intent result = new Intent();
            result.putStringArrayListExtra("result", list);
            setResult(RESULT_OK, result);
            takePhotoPath = null;
            finish();
        } else if (requestCode == REQUEST_PREVIEW && data != null) {
            ArrayList<String> deleteList = data.getStringArrayListExtra("data");
            if (deleteList != null && !deleteList.isEmpty()) {
                mAdapter.picked.removeAll(deleteList);
                mAdapter.notifyDataSetChanged();
                int size = mAdapter.picked.size();
                notifyTextChange(size);
            }
        }
    }

    @OnClick(R.id.tv_complete)
    void complete() {
        Intent result = new Intent();
        result.putStringArrayListExtra("result", mAdapter == null ? null : mAdapter.getPicked());
        setResult(RESULT_OK, result);
        finish();
    }

    @OnClick(R.id.tv_preview)
    void preview() {
        Intent intent = new Intent(this, PreviewActivity.class);
        intent.putStringArrayListExtra(PreviewActivity.IMAGE_PATH, mAdapter.getPicked());
        startActivityForResult(intent, REQUEST_PREVIEW);
        overridePendingTransition(R.anim.fade_enter, R.anim.fade_out);
    }

    private LoaderManager.LoaderCallbacks<Cursor> mLoaderCallback = new LoaderManager.LoaderCallbacks<Cursor>() {

        private final String[] IMAGE_PROJECTION = {
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Media.MIME_TYPE,
                MediaStore.Images.Media.SIZE,
                MediaStore.Images.Media._ID};

        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            return new CursorLoader(getApplicationContext(), MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION,
                    IMAGE_PROJECTION[4] + ">0 AND " + IMAGE_PROJECTION[3] + "=? OR " + IMAGE_PROJECTION[3] + "=? ",
                    new String[]{"image/jpeg", "image/png"}, IMAGE_PROJECTION[2] + " DESC");
        }

        private boolean fileExist(String path) {
            return !TextUtils.isEmpty(path) && new File(path).exists();
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            if (data != null && data.getCount() > 0) {
                List<String> images = new ArrayList<>();
                data.moveToFirst();
                do {
                    String path = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
                    if (!fileExist(path)) {
                        continue;
                    }
                    images.add(path);
                } while (data.moveToNext());

                mAdapter.setDatas(images);
            }
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {
        }
    };

}
